package org.thanos.demo.service;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thanos.demo.entity.menu.Menu;
import org.thanos.demo.vo.menu.MenuVo;

import java.util.List;
import java.util.stream.Collectors;

@Service("menuService")
public class MenuServiceImpl implements MenuService {

    @Override
    public List<MenuVo> queryAll() {
        List<MenuVo> menuVos = Menu.menus().stream().map(menu -> {
            MenuVo menuVo = new MenuVo();
            menuVo.setId(menu.getId());
            menuVo.setName(menu.getName());
            menuVo.setIcon(menu.getIcon());
            menuVo.setPath(menu.getPath());
            menuVo.setParentId(menu.getParentId());
            return menuVo;
        }).collect(Collectors.toList());
        return filter(menuVos, 0);
    }

    private List<MenuVo> filter(List<MenuVo> menuVos, Integer parentId) {
        List<MenuVo> childList = menuVos.parallelStream()
                .filter(menuVo -> menuVo.getParentId().equals(parentId))
                .collect(Collectors.toList());
        // 把子菜单的子菜单再循环一遍
        childList.forEach(menuVo -> menuVo.setChildren(this.filter(menuVos, menuVo.getId())));
        // 判断递归结束
        if (CollectionUtils.isEmpty(childList)) {
            return null;
        }
        return childList;
    }
}
